// pages/recipe/recipe.js
const app = getApp()

Page({
  data: {
    isGenerating: false,
    recipeData: null,
    shoppingList: [],
    healthTips: []
  },

  onLoad() {
    this.loadLastRecipe()
  },

  onShow() {
    this.loadLastRecipe()
  },

  onPullDownRefresh() {
    this.loadLastRecipe()
    wx.stopPullDownRefresh()
  },

  loadLastRecipe() {
    const lastRecipe = wx.getStorageSync('lastRecipe')
    if (lastRecipe) {
      this.setData({
        recipeData: lastRecipe.recipeData,
        shoppingList: lastRecipe.shoppingList || [],
        healthTips: lastRecipe.healthTips || []
      })
    }
  },

  // 生成食谱
  generateRecipe() {
    // 检查用户信息
    const userInfo = wx.getStorageSync('userInfo')
    const healthInfo = wx.getStorageSync('healthInfo')
    const foodList = wx.getStorageSync('foodList') || []

    if (!userInfo) {
      wx.showModal({
        title: '提示',
        content: '请先登录以使用食谱推荐功能',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            })
          }
        }
      })
      return
    }

    if (!healthInfo) {
      wx.showModal({
        title: '提示',
        content: '请先完善健康信息以获得个性化推荐',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/user-setting/user-setting'
            })
          }
        }
      })
      return
    }

    this.setData({ isGenerating: true })

    // 模拟生成过程
    setTimeout(() => {
      const recipeData = this.generateRecipeData(healthInfo, foodList)
      const shoppingList = this.generateShoppingList(recipeData, foodList)
      const healthTips = this.generateHealthTips(healthInfo)

      this.setData({
        isGenerating: false,
        recipeData,
        shoppingList,
        healthTips
      })

      // 保存到本地
      wx.setStorageSync('lastRecipe', {
        recipeData,
        shoppingList,
        healthTips,
        generateTime: new Date().toISOString()
      })

      // 添加到历史记录
      this.addToHistory(recipeData)

      app.showSuccess('食谱生成成功')
    }, 2000)
  },

  // 生成食谱数据
  generateRecipeData(healthInfo, foodList) {
    const isHighSugar = healthInfo.bloodSugar && healthInfo.bloodSugar > 6.1
    const isHighUricAcid = healthInfo.uricAcid && healthInfo.uricAcid > 420
    
    // 根据健康状态选择不同的食谱模板
    let recipeTemplate = 'normal'
    if (isHighSugar && isHighUricAcid) {
      recipeTemplate = 'both'
    } else if (isHighSugar) {
      recipeTemplate = 'sugar'
    } else if (isHighUricAcid) {
      recipeTemplate = 'uric'
    }

    const recipes = {
      both: {
        breakfast: {
          name: '燕麦蔬菜粥',
          ingredients: [
            { name: '燕麦', amount: 50, unit: 'g' },
            { name: '青菜', amount: 100, unit: 'g' },
            { name: '胡萝卜', amount: 50, unit: 'g' },
            { name: '鸡蛋', amount: 1, unit: '个' }
          ],
          steps: [
            '燕麦洗净，加水煮10分钟',
            '青菜、胡萝卜切碎加入粥中',
            '打入鸡蛋搅拌均匀',
            '煮5分钟即可食用'
          ],
          nutrition: { calories: 280, sugar: 5, protein: 15, purine: 25 }
        },
        lunch: {
          name: '清蒸鱼配杂粮饭',
          ingredients: [
            { name: '鲈鱼', amount: 150, unit: 'g' },
            { name: '杂粮米', amount: 100, unit: 'g' },
            { name: '西兰花', amount: 100, unit: 'g' },
            { name: '香菇', amount: 50, unit: 'g' }
          ],
          steps: [
            '鲈鱼清洗干净，切花刀',
            '杂粮米提前浸泡2小时',
            '所有食材一起蒸15分钟',
            '淋上少量生抽即可'
          ],
          nutrition: { calories: 350, sugar: 8, protein: 25, purine: 80 }
        },
        dinner: {
          name: '豆腐蔬菜汤',
          ingredients: [
            { name: '豆腐', amount: 150, unit: 'g' },
            { name: '西红柿', amount: 100, unit: 'g' },
            { name: '菠菜', amount: 100, unit: 'g' },
            { name: '金针菇', amount: 50, unit: 'g' }
          ],
          steps: [
            '所有蔬菜洗净切好',
            '水烧开后放入豆腐和蔬菜',
            '煮10分钟加少量盐',
            '最后放入菠菜煮1分钟'
          ],
          nutrition: { calories: 220, sugar: 6, protein: 12, purine: 30 }
        }
      },
      // 其他模板...
    }

    return recipes[recipeTemplate] || recipes.both
  },

  // 生成购买清单
  generateShoppingList(recipeData, foodList) {
    const allIngredients = [
      ...recipeData.breakfast.ingredients,
      ...recipeData.lunch.ingredients,
      ...recipeData.dinner.ingredients
    ]

    const shoppingList = []
    
    allIngredients.forEach(ingredient => {
      const existingFood = foodList.find(food => 
        food.name === ingredient.name && food.quantity >= ingredient.amount
      )
      
      if (!existingFood) {
        shoppingList.push({
          name: ingredient.name,
          amount: ingredient.amount,
          unit: ingredient.unit,
          checked: false,
          note: ''
        })
      }
    })

    return shoppingList
  },

  // 生成健康建议
  generateHealthTips(healthInfo) {
    const tips = []
    
    if (healthInfo.bloodSugar && healthInfo.bloodSugar > 6.1) {
      tips.push('控制主食摄入量，选择低GI食物')
      tips.push('避免含糖饮料和甜点')
      tips.push('定时定量进餐，避免暴饮暴食')
    }
    
    if (healthInfo.uricAcid && healthInfo.uricAcid > 420) {
      tips.push('限制高嘌呤食物摄入')
      tips.push('多喝水，促进尿酸排泄')
      tips.push('避免饮酒，特别是啤酒')
    }
    
    if (healthInfo.bmi && healthInfo.bmi > 24) {
      tips.push('控制总热量摄入，适当增加运动')
      tips.push('选择低脂高纤维食物')
    }
    
    if (tips.length === 0) {
      tips.push('保持均衡饮食，适量运动')
      tips.push('定期监测健康指标')
      tips.push('保持良好的作息习惯')
    }
    
    return tips
  },

  // 添加到历史记录
  addToHistory(recipeData) {
    const history = wx.getStorageSync('recipeHistory') || []
    const newRecord = {
      id: Date.now().toString(),
      date: app.formatDate(new Date()),
      breakfast: recipeData.breakfast.name,
      lunch: recipeData.lunch.name,
      dinner: recipeData.dinner.name,
      totalCalories: recipeData.breakfast.nutrition.calories + 
                   recipeData.lunch.nutrition.calories + 
                   recipeData.dinner.nutrition.calories
    }
    
    history.unshift(newRecord)
    if (history.length > 30) {
      history.splice(30) // 保留最近30条记录
    }
    
    wx.setStorageSync('recipeHistory', history)
  },

  // 收藏食谱
  collectRecipe(e) {
    const type = e.currentTarget.dataset.type
    const recipe = this.data.recipeData[type]
    
    const collections = wx.getStorageSync('recipeCollections') || []
    
    // 检查是否已收藏
    const existingIndex = collections.findIndex(item => 
      item.type === type && item.date === app.formatDate(new Date())
    )
    
    if (existingIndex === -1) {
      collections.unshift({
        id: Date.now().toString(),
        type: type,
        name: recipe.name,
        date: app.formatDate(new Date()),
        recipe: recipe
      })
      
      wx.setStorageSync('recipeCollections', collections)
      app.showSuccess('收藏成功')
    } else {
      app.showError('已收藏过今日食谱')
    }
  },

  // 分享食谱
  shareRecipe(e) {
    const type = e.currentTarget.dataset.type
    const recipe = this.data.recipeData[type]
    
    wx.showShareMenu({
      withShareTicket: true
    })
    
    app.showSuccess('已准备分享')
  },

  // 购物清单操作
  toggleShoppingItem(e) {
    const index = e.currentTarget.dataset.index
    const checked = e.detail.value.length > 0
    
    this.setData({
      [`shoppingList[${index}].checked`]: checked
    })
  },

  addNoteToShoppingList() {
    wx.showModal({
      title: '添加备注',
      content: '请输入备注内容',
      editable: true,
      success: (res) => {
        if (res.confirm && res.content) {
          // 这里可以添加备注到购物清单
          app.showSuccess('备注已添加')
        }
      }
    })
  },

  saveShoppingList() {
    const shoppingList = this.data.shoppingList
    wx.setStorageSync('shoppingList', shoppingList)
    app.showSuccess('购物清单已保存')
  }
})